package pervasivePositioning.androidPositioner;

import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;

import android.util.Log;

public class TCPClient {

	Socket sock;
	DataOutputStream dos;
	private String _serverIp;
	private int _port;
	//DataInputStream dis;

	public TCPClient(String serverIp, int port) throws IOException {
		this._serverIp = serverIp;
		this._port = port;
		//this.dis = new DataInputStream(sock.getInputStream());
	}

	public void sendReport(Report report) throws IOException
	{
		this.sock = new Socket(this._serverIp, this._port);
		this.dos = new DataOutputStream(sock.getOutputStream());
		dos.writeDouble(report.position.x);
		dos.writeDouble(report.position.y);
		dos.writeDouble(report.position.z);
		dos.writeLong(report.time);
		dos.writeBytes(report.strategyName + "\n");
		dos.writeBytes(report.configValue + "\n");
		dos.flush();
		Log.i("TCPClient", "Report flushed");
		close();
	}
	
	public void sendBytes(byte[] bytes) throws IOException
	{
		dos.writeByte(1);
		dos.writeInt(bytes.length);
		dos.write(bytes);
		dos.flush();
	}
	
	/**
	 * Close the connection to the server
	 * @throws IOException
	 */
	public void close() throws IOException {
		dos.writeByte(0);
		dos.flush();
		dos.close();
		sock.close();
	}
}
